package com.example.alibabanacosdiscoveryclient.service.impl;

import com.example.alibabanacosdiscoveryclient.domain.Order;
import com.example.alibabanacosdiscoveryclient.mapper.OrderMapper;
import com.example.alibabanacosdiscoveryclient.service.AccountService;
import com.example.alibabanacosdiscoveryclient.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author:guoq
 * @date:2024/11/21
 * @descripion:
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    AccountService accountService;

    @Override
    public List<Order> queryList() {
       return orderMapper.queryList();
    }

    @Override
    public int create(String userId, String commodityCode, int orderCount) throws Exception {

        int orderMoney = calculate(commodityCode, orderCount);

        int i=accountService.debit(userId, orderMoney);
        if(i==0){
            log.error("扣除账户余额失败");
            throw new Exception("账户余额不足");
        }
        Order order = new Order();
        order.userId = userId;
        order.commodityCode = commodityCode;
        order.count = orderCount;
        order.money = orderMoney;

        // INSERT INTO orders ...
        return orderMapper.insert(order);
    }
    private int calculate(String commodityId, int orderCount) {
        return 2 * orderCount;
    }
}
